
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class 购买黄金与收入的相关分析 {

    public static void main(String[] args) throws IOException {
        // 读取CSV文件
        CSVParser parser = CSVParser.parse(new FileReader("D:\\Marketing Campaign\\填充后的数据集.csv"),
                CSVFormat.DEFAULT.withFirstRecordAsHeader());

        // 存储数据
        List<Double> incomes = new ArrayList<>();
        List<Double> mntGoldProds = new ArrayList<>();

        for (CSVRecord record : parser) {
            incomes.add(Double.parseDouble(record.get("Income")));
            mntGoldProds.add(Double.parseDouble(record.get("MntGoldProds")));
        }

        // 计算相关系数
        PearsonsCorrelation correlation = new PearsonsCorrelation();
        double[] incomeArray = incomes.stream().mapToDouble(Double::doubleValue).toArray();
        double[] mntGoldProdsArray = mntGoldProds.stream().mapToDouble(Double::doubleValue).toArray();
        double correlationCoefficient = correlation.correlation(incomeArray, mntGoldProdsArray);
        System.out.println("相关系数矩阵：");
        System.out.println("Income, MntGoldProds");
        System.out.println("MntGoldProds, " + correlationCoefficient);

        // 绘制散点图与回归直线图
        XYSeries series = new XYSeries("Data");
        for (int i = 0; i < incomes.size(); i++) {
            series.add(incomes.get(i), mntGoldProds.get(i));
        }

        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(series);

        JFreeChart chart = ChartFactory.createScatterPlot(
                "年收入与购买黄金产品的总金额散点图",
                "年收入",
                "购买黄金产品的总金额",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        ChartFrame frame = new ChartFrame("Scatter Plot with Regression", chart);
        frame.pack();
        frame.setVisible(true);
    }
}